package com.loong.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * Created by 梁浩峰 on 2016/11/24 23:00.
 */
public class unZipMgr {
    public static void main(String[] args) {
        //源文件路径
        String sourcePath="D:\\logs\\log2.zip";
        //输出文件路径
        String outputPath="D:\\logs\\test";

        unZip(sourcePath, outputPath);

    }

    /**
     * 解压文件或文件夹
     * @param sourcePath
     * @param outputPath
     */
    private static void unZip(String sourcePath, String outputPath) {
        try {
            //文件输入流
            FileInputStream fin = new FileInputStream(sourcePath);
            //zip格式输入流
            ZipInputStream zin = new ZipInputStream(fin);
            ZipEntry zipEntry;
            while((zipEntry=zin.getNextEntry())!=null){
                //将压缩条目输出到输出路径
                File targetFile = new File(outputPath + File.separator + zipEntry.getName());

                //判断目标输出的父母是否存在，否创建
                if(!targetFile.getParentFile().exists()){
                    targetFile.getParentFile().mkdirs();
                }
                if(zipEntry.isDirectory()){
                    targetFile.mkdirs();
                }else{
                    FileOutputStream fout = new FileOutputStream(targetFile);
                    byte[] buff = new byte[1024];
                    int length;
                    while((length=zin.read(buff))>0){
                        fout.write(buff,0,length);
                    }
                    fout.close();
                }
            }
            zin.close();
            fin.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
